<template>
    <div class="break-snake">
        <canvas id="snake" width="900" height="600"></canvas>
        <el-button type="danger" @click="exIt">退出</el-button>
        <div class="container" v-if="gameOver">
            <div class="dialog">
                <p class="once-again">本轮分数：{{score}}分</p>
                <p class="once-again">真好玩！</p>
                <p class="once-again">再来一次~~</p>
                <el-button class="once-again-btn" @click="init">开始</el-button>
                <el-button type="danger" @click="back_home">退出</el-button>
            </div>
        </div>
    </div>
</template>

<script>
    import Common from '../components/common'
    const axios=require('axios')
    const randomColour=[
        "#d41313",
        "#e3b200",
        "#e35b00",
        "#00d254",
        "#002ed2",
        "#87c2b9",
        "#703caa",
        "#FFDC35",
        "#93FF93",
        "#d0d0d0"
    ];
    var fox_url=require("../assets/fox.jpeg");
    var bird_url=require("../assets/fox_bird.jpeg");
    export default {
        name: "snake",
        data(){
            return{
                username:'',
                size: 10,
                // 蛇
                snake: {
                    x:0,
                    y:0,
                    diRection:"left",
                    xSpeed: 5,
                    ySpeed: 5,
                    // height: 8,
                    // width: 100
                    size:100
                },
                Target: {
                    x: 0,
                    y: 0,
                    size:40,
                    dx: -2,
                    dy:-2
                },
                clientWidth: 0,
                clientHeight: 0,
                ctx: null,
                crushBalls: [],
                breaks:[],
                gameOver:false,
                score:0
            }
        },
        mounted() {
            let _this=this;
            _this.username=this.$cookies.get("username");
            console.log(_this.username)
            let container=document.getElementById("snake")
            this.ctx=container.getContext("2d");
            this.clientHeight=container.height;
            this.clientWidth=container.width;
            _this.init();
            document.onkeydown = function(e) {
                let key = window.event.keyCode;
                if (key === 37  || event.keyCode==65) {
                    _this.snake.diRection="left"
                    _this.snakeMove();
                } else if (key === 39  || event.keyCode==68) {
                    // 右键 或D
                    _this.snake.diRection="right"
                    _this.snakeMove();
                }
                else if(key==40){
                    //向上
                    _this.snake.diRection="up"
                    _this.snakeMove();
                }
                else if(key==38){
                    //向下
                    _this.snake.diRection="down"
                    _this.snakeMove();
                }
            }
            document.onkeyup=function (e) {
                // _this.pannel.dx=0;
            };

            (function animloop() {
                if (!_this.gameOver) {
                    _this.moveTarget();
                    _this.drawAll();
                    _this.snakeMove();
                    _this.updateSnake();
                }
                else{
                    _this.drawCrushBreaks();
                }
                window.requestAnimationFrame(animloop);
            })();
        },

        methods:{
            init(){
                let _this = this;
                _this.score=0;
                _this.gameOver = false;
                this.snake.y = (this.clientHeight - this.snake.size)/2;
                this.snake.x = this.clientWidth / 2 - this.snake.size / 2;
                this.Target.y = this.clientHeight / 2;
                this.Target.x = this.clientWidth / 2;
            },

            exIt(){
                this.gameOver=true
                let data=new URLSearchParams()
                data.append('username',this.username)
                data.append('snake',this.score)
                axios.post('/user/updatesnake',data).then(res =>{
                    console.log(res)
                })
                this.getCurshBreaks()
            },

            back_home(){
                this.$router.push("/home");
            },
            drawSnake(){
                var img = new Image();
                img.src=fox_url;
                this.ctx.drawImage(img,this.snake.x,this.snake.y,this.snake.size,this.snake.size)
                //this.ctx.fillStyle="#e20b0b"
                this.ctx.fill();
                //this.ctx.fillRect(this.snake.x,this.snake.y,30,30)
            },

            drawAll(){
              this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
              this.drawSnake();
              this.drawTarget();
              this.drawScore();
            },
            drawTarget() {
                var img = new Image();
                img.src=bird_url;
                this.ctx.drawImage(img,this.Target.x,this.Target.y,this.Target.size,this.Target.size)
                // this.ctx.beginPath();
                // this.ctx.arc(this.Target.x,this.Target.y,this.Target.r,0,2*Math.PI);
                // this.ctx.fillStyle = "#008b8b";
                this.ctx.fill();
                // this.ctx.closePath();

            },
            moveTarget() {
                this.Target.x += this.Target.dx;
                this.Target.y += this.Target.dy;
                // this.breaksHandle();
                this.edgeHandle();
            },

            edgeHandle(){
                if(this.Target.x-this.Target.size<0 || this.Target.x+this.Target.size>=this.clientWidth){
                    this.Target.dx = -this.Target.dx;
                }
                if(this.Target.y-this.Target.size<=0 || this.Target.y+this.Target.size>=this.clientHeight){
                    this.Target.dy = -this.Target.dy;
                }
                if(this.snake.x===this.Target.x+this.Target.size || this.snake.y===this.Target.y-this.Target.size){
                    this.Target.x=this.getRandomArbitrary(30,this.clientWidth)
                    //this.Target.y=this.getRandomArbitrary(30,this.clientHeight)
                     //this.Target.r--;
                    this.score++;
                }
                // if(this.ball.x>=this.Target.x
                //     && this.ball.x<=this.Target.x+this.Target.width
                //     && (this.ball.y - this.ball.r <= this.Target.y+this.Target.height))
                // {
                //     this.ball.dy=-this.ball.dy;
                //     this.ball.dx=-this.ball.dx
                //     this.score++;
                //     this.Target.dx+=0.3;
                //     this.Target-=0.5
                // }
                if(this.Target.y-this.Target.size<0){
                    this.Target.dy=-this.Target.dy;
                }
                // if(this.Target.x-this.pannel.x>=0
                //     && this.ball.x<=this.pannel.x+this.pannel.width
                //     && this.ball.y + this.ball.r >= this.clientHeight - this.pannel.height){
                //     this.ball.dy=-this.ball.dy;
                //     this.score+=0.5;
                // }
                // else if((this.Target.x < this.pannel.x
                //     || this.ball.x > this.pannel.x + this.pannel.width) &&
                //     this.ball.y + this.ball.r >= this.clientHeight){
                //     this.gameOver=true;
                //     this.getCurshBreaks();
                // }
            },

            updateSnake() {
                this.snake.x += this.snake.xSpeed;
                this.snake.y += this.snake.ySpeed;
            },
            getRandomArbitrary(min, max) {
                return Math.random()*(max-min)+min;
            },
            Move(xStep,yStep){
                (this.snake.xSpeed = xStep),
                    (this.snake.ySpeed = yStep);
                if(this.snake.x+this.snake.size>=this.clientWidth)
                    {
                        this.snake.diRection="left"
                    }
                    if(this.snake.y<=0)
                    {
                        this.snake.diRection="up"
                    }
                    if(this.snake.y>=this.clientHeight)
                    {
                        this.snake.y=0
                    }
                    if(this.snake.x<=0)
                    {
                         this.snake.x=this.clientWidth
                    }
            },

            snakeMove(){
                switch (this.snake.diRection) {
                    case "left":
                        this.Move(-4,0);
                        break;
                    case "right":
                        this.Move(4,0);
                        break;
                    case "up":
                        this.Move(0,4);
                        break;
                    case "down":
                        this.Move(0,-4);
                        break;
                    default:
                        break;
                }
            },
            drawScore(){
                this.ctx.beginPath();
                this.ctx.font="14px Arial";
                this.ctx.fillStyle = "#FFF";
                this.ctx.fillText("分数："+this.score,10,this.clientHeight-14);
                this.ctx.closePath();
            },

            getRandomColor(){
                return randomColour[Math.floor(Math.random() * randomColour.length)];
            },

            getCurshBreaks() {
                let _this = this;
                for (let i = 0; i < 10+_this.score*5; i++) {
                    this.crushBalls.push({
                        x: 5,
                        y: 5,
                        dx: _this.getRandomArbitrary(-6, 6),
                        dy: _this.getRandomArbitrary(-6, 6),
                        r: _this.getRandomArbitrary(1, 4),
                        color: _this.getRandomColor()
                    });
                }
            },

            drawCrushBreaks() {
                this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
                this.crushBalls.forEach(item => {
                    this.ctx.beginPath();
                    this.ctx.arc(item.x, item.y, item.r, 0, 2 * Math.PI);
                    this.ctx.fillStyle = item.color;
                    this.ctx.fill();
                    this.ctx.closePath();
                    item.x += item.dx;
                    item.y += item.dy;
                    if (
                        // 碰到左右墙壁
                        item.x - item.r < 0 ||
                        item.x + item.r > this.clientWidth
                    ) {
                        item.dx = -item.dx;
                    }
                    if (
                        // 碰到上下墙壁
                        item.y - item.r < 0 ||
                        item.y + item.r > this.clientHeight
                    ) {
                        item.dy = -item.dy;
                    }
                });
            },
        }



    }
</script>

<style lang="scss" scoped>
    .break-snake {
        width: 900px;
        height: 600px;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        position: absolute;
        #snake {
            background-image: url("../assets/snake_background.jpg");
        }
        margin: auto;
        .container {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: rgba(0, 0, 0, 0.3);
            text-align: center;
            font-size: 0;
            white-space: nowrap;
            overflow: auto;
        }
        .container:after {
            content: "";
            display: inline-block;
            height: 100%;
            vertical-align: middle;
        }
        .dialog {
            width: 400px;
            height: 300px;
            background: rgba(255, 255, 255, 0.5);
            box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, 0.3);
            display: inline-block;
            vertical-align: middle;
            text-align: left;
            font-size: 28px;
            color: #fff;
            font-weight: 600;
            border-radius: 10px;
            white-space: normal;
            text-align: center;
            .once-again-btn {
                background: #1f9a9a;
                border: none;
                color: #fff;
            }
        }
    }
</style>